<script setup>
import {
    Download,
    Delete,
    Edit,
    Plus
} from '@element-plus/icons-vue'
import { ref, computed, watch } from 'vue'
// 调用接口,添加表单
import { ElMessage, ElMessageBox } from 'element-plus'
//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

import { useRouter } from "vue-router";
// 路由对象
const router = useRouter();

const errorMsg = ref("");     // 上传文件的错误消息
const uploadRef = ref(null);  // 上传文件 

// 控制抽屉是否显示
const visibleDrawer = ref(false)
// 是否为编辑考试
const isEditing = ref(false)

// 关闭抽屉
const closeDrawer = () => {
    visibleDrawer.value = false;
    resetForm();
};

// 编辑考试，填充已有数据
const editExam = (exam) => {
    isEditing.value = true;
    // 填充现有考试数据
    examData.value = { ...exam };  // 通过复制 exam 对象填充数据
    // 显示抽屉
    visibleDrawer.value = true;
};

// 检测上传信息是否完整，以判断是否能够提交请求
const canSubmit = computed(() => {
    return (
        examData.value.e_name &&
        examData.value.startTime &&
        examData.value.endTime &&
        examData.value.q_name &&
        examData.value.q_path
    );
});

// 按下抽屉中“保存”键后，根据情景不同调用相关函数
const handleSubmit = () => {
    isEditing.value ? updateExam() : addExam();
    closeDrawer();
};


// 示例数据
const exams = ref([
    {
        "e_id": 1,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
    },
    {
        "e_id": 2,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
    },
    {
        "e_id": 3,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
    },
    {
        "e_id": 4,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
    },
    {
        "e_id": 5,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
    },
    {
        "e_id": 6,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
    },
    {
        "e_id": 7,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
    },
    {
        "e_id": 8,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
    },
    {
        "e_id": 9,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
    },
]);


// 定义考试数据模型
const examData = ref({
    e_id: null,         // 考试 ID（新增考试时为空）
    e_name: '',         // 考试名称
    startTime: null,    // 考试开始时间
    endTime: null,      // 考试结束时间
    e_autostart: false, // 是否自动开始
    q_path: '',         // 试卷文件路径
    q_name: ''          // 试卷名称
});


// 分页后的考试数据
const paginatedExams = computed(() => {
    const start = (pageNum.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return exams.value.slice(start, end);
});



// 跳转到考生管理页面
function navigateToAddStudents(row) {
    router.push({
        path: "/exam/addStudents",
        query: {
            e_id: row.e_id,
            e_name: row.e_name,
            startTime: row.startTime,
            endTime: row.endTime,
            q_path: row.q_path,
            q_name: row.q_name,
        },
    });
}


// 根据考试时间判断考试状态
const calculateExamStatus = (startTime, endTime) => {
    const now = new Date();
    const start = new Date(startTime);
    const end = new Date(endTime);

    if (now < start) return "未开始";
    if (now >= start && now <= end) return "进行中";
    return "已结束";
};

// 根据考试状态设置字体样式
const getStatusClass = (status) => {
    switch (status) {
        case "未开始":
            return "status-blue";
        case "进行中":
            return "status-green";
        case "已结束":
            return "status-red";
        default:
            return "";
    }
};


//声明一个异步的函数
import { examListService, examAddService, examUpdateService, examDeleteService, examSearchService, examDownloadZipService } from '@/api/examNew.js'

// 获取考试列表
const getExamList = async () => {
    let result = await examListService();
    exams.value = result.data;
}
// 调用
getExamList();

// 查询方法
const searchExam = async () => {
    try {
        let result = await examSearchService(examData.value.e_name);
        exams.value = result.data;
    } catch (error) {
        ElMessage.error('查询考试失败');
    }
    // 这里补充实际查询逻辑
};

// 更新学生信息
const updateExam = async () => {
    try {
        // 调用学生信息修改接口
        let result = await examUpdateService(examData.value);
        // 根据服务端返回的msg信息是否为空，判断是否更新成功
        ElMessage.success(result.msg ? result.msg : '考试信息已更新');
        // 刷新考试列表
        getExamList();
    } catch (error) {
        ElMessage.error('考试信息编辑请求超时');
    }
    closeDrawer();
};

// 新增考试方法
const addExam = async () => {
    try {
        let result = await examAddService(examData.value);
        // 根据服务端返回的msg信息是否为空，判断是否添加成功
        ElMessage.success(result.msg ? result.msg : '考试已添加');

    } catch (error) {
        ElMessage.error('添加考试请求超时');
    }
    // 刷新考试列表
    getExamList();
    closeDrawer();
};

// 打包下载方法
const downloadZip = (id, name) => {
    console.log('下载考试 ID:', id, '名称:', name);
    // 补充下载逻辑

};

// 删除考试方法
const removeExam = (e_id) => {
    // 提示用户确认框
    ElMessageBox.confirm(
        '你确认要删除该考试信息吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 调用删除接口
                let result = await examDeleteService(e_id);

                // 判断接口返回的结果，确保删除成功
                if (result && result.success) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    });
                    // 刷新考试列表
                    getExamList();
                } else {
                    // 如果删除失败，给出失败提示
                    ElMessage({
                        type: 'error',
                        message: result.message || '删除失败，请稍后再试。',
                    });
                }
            } catch (error) {
                // 捕获删除过程中出现的错误
                ElMessage({
                    type: 'error',
                    message: error.message || '删除过程中发生了错误，请稍后再试。',
                });
            }
        })
        .catch(() => {
            // 用户取消删除操作
            ElMessage({
                type: 'info',
                message: '用户取消了删除',
            });
        });
};

// 重置考试列表
const resetExamList = () => {
    resetForm();
    getExamList();
}

// 重置表单方法
const resetForm = () => {
    examData.value = {
        e_id: null,
        e_name: '',
        startTime: null,
        endTime: null,
        e_autostart: false,
        q_path: '',
        q_name: ''
    };
    console.log('表单已重置');
};


// 校验文件类型和大小
const handleFileChange = (file, fileList) => {
    // upfilelist.value = fileList;

    ElMessage.success('diaoyong')

    // 如果文件列表为空，清空错误信息
    if (fileList.length === 0) {
        ElMessage.success('diaoyong22222')
        errorMsg.value = "";
        ElMessage.info("已清空");
        return;
    }

    // 获取第一个文件
    const currentFile = fileList[0].raw;

    // 校验文件类型和大小
    const validTypes = [
        "image/png",
        "image/jpeg",
        "application/zip",
        "application/x-7z-compressed",
        "application/x-rar-compressed",
    ];
    const maxSize = 20 * 1024 * 1024; // 20MB

    if (!validTypes.includes(currentFile.type)) {
        errorMsg.value =
            "文件格式不正确，仅支持图片文件或压缩包文件（PNG、JPEG、ZIP、RAR、7Z）";
        fileList.splice(0); // 清空文件列表
        return;
    }

    if (currentFile.size > maxSize) {
        errorMsg.value = "文件大小不能超过 20MB";
        // fileList.splice(0); // 清空文件列表
        return;
    }

    // 校验通过
    errorMsg.value = "";
    isUploadEnabled.value = true;
    examData.value.q_name = currentFile.name;
    ElMessage.success('diaoyong333333')

    // 触发上传
    if (uploadRef.value) {
        uploadRef.value.submit(); // 手动触发上传
    }
};

// 上传文件成功回调
const uploadFileSuccess = (result) => {
    ElMessage.success('文件上传成功');
    examData.value.q_path = result.data;   // 将文件下载路径赋值给 examData
};



// 分页数据
const pageNum = ref(1); // 当前页
const pageSize = ref(3); // 每页条数
const total = ref(exams.value.length); // 总条数

// 页大小改变
const onSizeChange = (size) => {
    pageSize.value = size;
    pageNum.value = 1; // 重置到第一页
};

// 页码改变
const onPageChange = (page) => {
    pageNum.value = page;
};

// 监听 exams 数组变化，实时更新 total 值
watch(
    () => exams.value,
    (newVal) => {
        total.value = newVal.length;
    },
    { deep: true }
);



</script>


<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>考试管理</span>
                <div class="extra">
                    <el-button type="primary"
                        @click="resetForm(), visibleDrawer = true, isEditing = false">新增考试</el-button>
                </div>
            </div>
        </template>

        <!-- 根据考试名称查询某场考试or新增考试信息 -->
        <el-form :model="examData" inline style="margin-bottom: 20px">
            <el-form-item label="考试名称">
                <el-input v-model="examData.e_name" placeholder="请输入考试名称" clearable />
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="examData.e_autostart">自动开始</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchExam">查询</el-button>
                <el-button type="default" @click="resetExamList">重置</el-button>
            </el-form-item>
        </el-form>

        <h1>{{ examData }}</h1>
        <hr>
        <h1>{{ visibleDrawer }}</h1>
        <!-- 考试列表 -->
        <el-table :data="paginatedExams" style="width: 100%">
            <el-table-column label="名称(ID)">
                <template #default="{ row }">
                    {{ row.e_name }}(ID:{{ row.e_id }})
                </template>
            </el-table-column>
            <el-table-column label="开始时间">
                <template #default="{ row }">{{ row.startTime }}</template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template #default="{ row }">{{ row.endTime }}</template>
            </el-table-column>
            <el-table-column label="试卷">
                <!-- <template #default="{ row }">
                    <el-link type="primary" :href="`${basePath}download?filepath=${row.q_path}&filename=${row.q_name}`">
                        {{ row.q_name }}
                    </el-link>
                </template> -->
                <template #default="{ row }">
                    <template v-if="row.q_path">
                        <a :href="row.q_path" :download="row.q_name">{{ row.q_name }}</a>
                    </template>
                    <span v-else>未上传</span>
                </template>
            </el-table-column>
            <el-table-column label="考试状态">
                <template #default="{ row }">
                    <span :class="getStatusClass(calculateExamStatus(row.startTime, row.endTime))">
                        {{ calculateExamStatus(row.startTime, row.endTime) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="考试编辑">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="editExam(row)"></el-button>
                </template>
            </el-table-column>
            <el-table-column label="归档下载">
                <template #default="{ row }">
                    <el-button :icon="Download" circle plain type="primary"
                        @click="downloadZip(row.e_id, row.e_name)"></el-button>
                </template>
            </el-table-column>
            <el-table-column label="考生管理">
                <template #default="{ row }">
                    <el-button :icon="Plus" circle plain type="primary" @click="navigateToAddStudents(row)"></el-button>
                </template>
            </el-table-column>
            <el-table-column label="删除考试">
                <template #default="{ row }">
                    <el-button :icon="Delete" circle plain type="danger" @click="removeExam(row.e_id)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有考试数据" />
            </template>
        </el-table>

        <!-- 分页条   5555-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onPageChange" style="margin-top: 20px; justify-content: flex-end" />


        <!-- 抽屉 (添加考试时或者编辑考试时上传相关文件) -->
        <el-drawer v-model="visibleDrawer" :title="isEditing ? '编辑考试信息' : '添加考试'" direction="rtl" size="40%">
            <!-- 添加考试表单 -->
            <el-form :model="examData" label-width="100px">
                <!-- 考试标题 -->
                <el-form-item label="考试标题" :rules="[{ required: true, message: '请输入考试标题', trigger: 'blur' }]">
                    <el-input v-model="examData.e_name" placeholder="请输入标题" clearable />
                </el-form-item>

                <!-- 文件名称和下载路径 (不可编辑) -->
                <el-form-item label="文件名称" :rules="[{ required: true }]">
                    <el-input v-model="examData.q_name" :disabled="true" placeholder="文件名称" />
                </el-form-item>
                <el-form-item label="下载路径" :rules="[{ required: true }]">
                    <el-input v-model="examData.q_path" :disabled="true" placeholder="下载路径" />
                </el-form-item>

                <!-- 开始时间 -->
                <el-form-item label="开始时间" :rules="[{ required: true, message: '请选择开始时间', trigger: 'change' }]">
                    <el-date-picker v-model="examData.startTime" type="datetime" placeholder="选择开始时间" clearable />
                </el-form-item>

                <!-- 结束时间 -->
                <el-form-item label="结束时间" :rules="[{ required: true, message: '请选择结束时间', trigger: 'change' }]">
                    <el-date-picker v-model="examData.endTime" type="datetime" placeholder="选择结束时间" clearable />
                </el-form-item>

                <!-- 上传文件 -->
                <el-form-item label="上传文件" :rules="[{ required: true, message: '请选择上传文件', trigger: 'change' }]">
                    <el-upload class="file-uploader" action="/api/upload" name="file"
                        :headers="{ 'Authorization': tokenStore.token }" :file-list="fileList" :auto-upload="false"
                        :limit="1" :on-change="handleFileChange" ref="uploadRef" :on-success="uploadFileSuccess">
                        <el-button slot="trigger" type="primary">选择试卷文件</el-button>
                    </el-upload>
                    <el-alert v-if="errorMsg" :title="errorMsg" type="error" show-icon closable
                        style="margin-top: 10px" />
                </el-form-item>

                <!-- 发布按钮 -->
                <el-form-item>
                    <el-button :type="canSubmit ? 'primary' : 'info'" :disabled="!canSubmit" @click="handleSubmit">
                        {{ canSubmit ? isEditing ? '修改该考试' : '发布该考试' : '请完善信息' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-form-item {
        margin-bottom: 10px;
    }

    .status-blue {
        color: rgb(26, 154, 214);
    }

    .status-green {
        color: rgb(26, 223, 118);
    }

    .status-red {
        color: rgb(234, 15, 15);
    }
}

/* 抽屉样式 */
.examfile-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.examfile-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.file-uploader {
    width: 100%;
}
</style>